<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span{
            margin-left: 20px;
        }
        .red{
            background-color: red;
        }
    </style>
</head>
    <ul>
        <li>1<span>x</span></li>
        <li>2<span>x</span></li>
        <li>3<span>x</span></li>
        <li>4<span>x</span></li>
    </ul>
    <button>新增</button>
<body>
</body>
    <script>
        let selectli
        let ul=document.querySelector('ul')
        //点击li的事件委托给ul
        ul.onclick=function(e){
            if(e.target.tagName=='LI'||e.target.tagName=='SPAN'){
                //除去上次被选中的li的样式
                if(selectli){
                    selectli.classList.remove('red')
                }
                //本次点击的li新增样式
                let clickli=e.target.tagName=='LI'?e.target:e.target.parentElement
                clickli.className+=' red'
                selectli=clickli
            }
        }
        //新增事件
        document.querySelector('button').onclick=function(){
            //创建新li
            let newli=document.createElement('li')
            newli.innerHTML=(Math.random()*10|0)+'<span>x</span>'
            //如果存在被选中的li，就在它前面插入新li
            if(selectli){
                ul.insertBefore(newli,selectli)
            }
        }
    </script>
</html>